from dataclasses import dataclass
import os
import uuid

from flask import request, jsonify
from injector import inject
from openai import OpenAI

from internal.schema.app_schema import CompletionReq
from internal.service import app_service
from pkg.response import Response, HttpCode
from internal.service import AppService
from pkg.response.response import success_message
@inject
@dataclass
class AppHandler:
    app_service: AppService

    def create_app(self):
       app= self.app_service.create_app()
       return  success_message(f'应用创建成功,id为{app.id}')


    def get_app(self,id:uuid.UUID):
        app=self.app_service.get_app(id)
        return success_message(f'获取应用成功为{app.name}')

    def update_app(self,id:uuid.UUID):
        app=self.app_service.update_app(id)
        return success_message(f'更新应用名词成功,名为:{app.name}')

    def delete_app(self,id:uuid.UUID):
        app=self.app_service.delete_app(id)
        return success_message(f'删除应用成功,id为:{app.name}')

    def completion(self):
        # 数据的校验
        req = CompletionReq()
        if not req.validate():
            return req.errors
        # 获取请求对象中的参数query
        query = request.json.get("query")
        # 创建OpenAi客户端
        client = OpenAI(
            api_key=os.getenv("OPENAI_API_KEY"),
            # 在这里将 MOONSHOT_API_KEY 替换为你从 Kimi 开放平台申请的 API Key
            base_url=os.getenv("OPENAI_API_BASE"),
        )
        completion = client.chat.completions.create(
            model="moonshot-v1-8k",
            messages=[
                {"role": "system",
                 "content": "你是个聊天机器人,请基于用户的问题进行回答"},
                {"role": "user", "content": query}
            ],
        )
        content = completion.choices[0].message.content
        resp = Response(code=HttpCode.SUCCESS, message="", data={"content": content})

        return jsonify(resp), 200
        # 应用控制器

    def ping(self):
        return {"ping": "lzh测试应用控制器返回的对象"}
